const Router = require('@koa/router')
const fs = require('fs')

const router = new Router()

// 配置路由
router.get('/a', async(ctx)=>{
    console.log('get => /a', ctx.query);
    await new Promise(resolve => {
        setTimeout(() => {
            resolve()
        }, 2000);
    })
    ctx.body = JSON.stringify({x:1})
    ctx.set('Content-type', 'application/json')
})

router.post('/a', async(ctx)=>{
    let body = ctx.request.body
    console.log('post => /a body', body,  typeof body);

    ctx.body = JSON.stringify({x:1})
    ctx.set('Content-type', 'application/json')
})

router.post('/b', async(ctx)=>{
    let body = ctx.request.body
    console.log('post => /b body', body,  typeof body);

    ctx.body = JSON.stringify({x:1})
    ctx.set('Content-type', 'application/json')
})

// 上传文件
router.post('/upload', async(ctx)=>{
    // console.log(ctx.request.body);
    // console.log(ctx.request.files);
    ctx.body = JSON.stringify(ctx.request.files)
    ctx.set('Content-type', 'application/json')

    // 复制文件
    let file = ctx.request.files['bbb']
    console.log(fs.existsSync(file.path)) // true 文件已经保存
    let picReadStream = fs.createReadStream(file.path)
    let picWriteStream = fs.createWriteStream('./backup/' + new Date().getTime() +file.name)
    picReadStream.pipe(picWriteStream)
})

// 'Content-Type': 'application/octet-stream'
router.put('/upload', async (ctx)=>{
    let data = []
    try {
        await new Promise(resolve => {
            // ctx.req.on('data', (chunk) => {
            //     data.push(chunk)
            //     console.log('on data');
            // })
            // ctx.req.on('end', () => {
            //     console.log('on end');

            //     let buffer = Buffer.concat(data)
            //     console.log(buffer.length);
            //     if (buffer.length) {
            //         fs.writeFileSync('./public/temp/' + new Date().getTime() + '.png', buffer, function(err) {
            //             if(err) {console.log(err)}
            //         });
            //     }

            //     resolve()
            // })
            let ws = fs.createWriteStream('./public/temp/' + new Date().getTime() + '.png')
            ctx.req.on('data', (chunk) => {
                ws.write(chunk)
            })
            ctx.req.on('end', () => {
                ws.end()
                resolve()
            })
        })
    } catch (error) {
        console.log('error', error);
    }

    ctx.body = JSON.stringify({success:1})
    ctx.set('Content-type', 'application/json')
})

// 下载文件
router.get('/download', async(ctx)=>{
    // ctx.set('Content-type', 'application/octet-stream')
    // ctx.set('Content-type', 'multipart/form-data')
    ctx.set('Content-type', 'image/png') // 直接访问 http://localhost:3000/download , 浏览器中直接显示图片

    // ctx.set('Content-Disposition', 'attachment;fileName=a.png') // 增加这个响应头, 直接访问 http://localhost:3000/download 浏览器中会下载文件

    let filePath = './public/upload/upload_cadafa60f32e092a45a31ab4ec92f4eb.png'
    // ----1----
    // const reader = fs.readFileSync(filePath);
    // ctx.body = reader;
    // ----1----

    // ----2----
    ctx.body = fs.createReadStream(filePath)
    // ----2----
})

module.exports = router


